#!/usr/bin/env python
#  -*- coding: utf-8 -*-

# Tiago Falcao RA 046802
# Programa Servidor para Impressao via Invocação Remota

import Pyro.core
import Pyro.naming
import sqlite3

class Printer(Pyro.core.ObjBase):

        def __init__(self):
		"Inicia Objeto Remoto"
                Pyro.core.ObjBase.__init__(self)

        def Print(self, user, password, pages):
		"Simula impressao de 'pages' paginas do usuario 'user' com a senha 'password'"
		if user==password:
			log = sqlite3.connect('log.sqlite')
			log.execute("INSERT INTO Log(user,pages) VALUES('"+user+"',"+str(pages)+")")
			log.commit()
			print "PRINT",pages,"pages from",user
                	return True
		else:
			return False

        def CountAll(self):
		"Retorna numero de paginas impressas pelo impressora"
		log = sqlite3.connect('log.sqlite')
                ret = log.execute("SELECT sum(pages) FROM Log").fetchall()
		log.close()
		return ret[0][0]

        def Count(self, user):
		"Retorna numero de paginas impressas pelo usuario 'user'"
		log = sqlite3.connect('log.sqlite')
                ret=log.execute("SELECT sum(pages) FROM Log WHERE user='"+user+"'").fetchall()
		log.close()
		return ret[0][0]

	def ListUsers(self):
		"Retorna lista de usuarios de usuarios e suas quantidades impressas em lista de tuplas (usuario,numero de paginas) ordenadas em ordem decrescente"
		log = sqlite3.connect('log.sqlite')
                ret=log.execute("SELECT user,sum(pages) FROM Log GROUP BY user ORDER BY sum(pages) DESC").fetchall()
		log.close()
		return ret

	def LogUser(self,user):
		"Retorna log do usuario 'user' em lista de tuplas (tempo,numero de paginas)"
		log = sqlite3.connect('log.sqlite')
                ret=log.execute("SELECT time,pages FROM Log WHERE user='"+user+"' ORDER BY time DESC").fetchall()
		log.close()
		return ret
	

def main():
	# Cria Banco de Dados e Tabela de Log se nao existirem
	log = sqlite3.connect('log.sqlite')
	log.execute("CREATE  TABLE  IF NOT EXISTS 'Log' ('id' INTEGER PRIMARY KEY  NOT NULL  DEFAULT '', 'user' VARCHAR NOT NULL  DEFAULT '', 'pages' INTEGER NOT NULL  DEFAULT '', 'time' DATETIME NOT NULL  DEFAULT CURRENT_TIMESTAMP)")
	log.close()
	
	#Inicia Pyro
	Pyro.core.initServer()
	daemon=Pyro.core.Daemon()


	#Registra no NameServer se este estiver ativo
	try:
		ns=Pyro.naming.NameServerLocator().getNS()
		daemon.useNameServer(ns)
	except Pyro.errors.NamingError:
		pass

	#Registra
	uri=daemon.connect(Printer(),"printer")

	print "The daemon runs on port:",daemon.port
	print "The object's uri is:",uri

	#Loop de Espera de Requisicoes
	daemon.requestLoop()
	

if __name__=="__main__":
	main()

